<template>
  <el-dialog
    :title="title"
    v-model="dialogVisible"
    width="500px"
    append-to-body
    destroy-on-close
  >
    <el-form ref="formRef" :model="form" :rules="rules" label-width="80px">
      <el-form-item label="成员" prop="memberId">
        <el-select
          v-model="form.memberId"
          placeholder="请选择成员"
          clearable
          class="!w-380px"
          @change="handleMemberChange"
        >
          <el-option
            v-for="item in memberOptions"
            :key="item.id"
            :label="item.name"
            :value="item.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="关系类型" prop="relationType">
        <el-select
          v-model="form.relationType"
          placeholder="请选择关系类型"
          clearable
          class="!w-380px"
        >
          <el-option
            v-for="dict in getStrDictOptions(DICT_TYPE.FAMILY_RELATIONSHIP_TYPE)"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="关联成员" prop="relatedMemberId">
        <el-select
          v-model="form.relatedMemberId"
          placeholder="请选择关联成员"
          clearable
          class="!w-380px"
          :disabled="!form.memberId"
        >
          <el-option
            v-for="item in relatedMemberOptions"
            :key="item.id"
            :label="item.name"
            :value="item.id"
          />
        </el-select>
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="cancel">取 消</el-button>
      <el-button type="primary" @click="submitForm">确 定</el-button>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { RelationshipsApi } from '@/api/family/relationships'
import { MembersApi } from '@/api/family/members'
import { DICT_TYPE, getStrDictOptions } from '@/utils/dict'

const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗

const dialogVisible = ref(false) // 弹窗是否打开
const title = ref('') // 弹窗标题
const form = ref({
  id: undefined,
  memberId: undefined,
  relationType: undefined,
  relatedMemberId: undefined
})
const rules = reactive({
  memberId: [{ required: true, message: '成员不能为空', trigger: 'change' }],
  relationType: [{ required: true, message: '关系类型不能为空', trigger: 'change' }],
  relatedMemberId: [{ required: true, message: '关联成员不能为空', trigger: 'change' }]
})

const formRef = ref() // 表单 Ref
const memberOptions = ref<Array<{id: number, name: string}>>([]) // 成员选项
const relatedMemberOptions = ref<Array<{id: number, name: string}>>([]) // 关联成员选项

/** 打开弹窗 */
const open = (type: string, id?: number) => {
  dialogVisible.value = true
  title.value = type === 'create' ? '新增关系' : '修改关系'
  if (id) {
    // 修改时，加载数据
    loadData(id)
  } else {
    // 新增时，重置表单
    reset()
  }
  // 加载成员选项
  loadMemberOptions()
}

/** 加载数据 */
const loadData = async (id: number) => {
  try {
    const data = await RelationshipsApi.getRelationships(id)
    form.value = data
  } catch {}
}

/** 加载成员选项 */
const loadMemberOptions = async () => {
  try {
    const data = await MembersApi.getMembersPage({
      pageNo: 1,
      pageSize: 1000,
      name: undefined,
      gender: undefined,
      birthDate: [],
      deathDate: [],
      contactInfo: undefined,
      photoUrl: undefined,
      biography: undefined,
      generation: undefined,
      createTime: []
    })
    memberOptions.value = data.list
  } catch {}
}

/** 成员选择变更 */
const handleMemberChange = async (memberId: number) => {
  if (!memberId) {
    relatedMemberOptions.value = []
    form.value.relatedMemberId = undefined
    return
  }
  // 加载可选的关联成员
  try {
    const data = await MembersApi.getMembersPage({
      pageNo: 1,
      pageSize: 1000,
      name: undefined,
      gender: undefined,
      birthDate: [],
      deathDate: [],
      contactInfo: undefined,
      photoUrl: undefined,
      biography: undefined,
      generation: undefined,
      createTime: []
    })
    // 过滤掉当前选中的成员
    relatedMemberOptions.value = data.list.filter(item => item.id !== memberId)
  } catch {}
}

/** 提交按钮 */
const submitForm = async () => {
  // 表单校验
  if (!formRef.value) return
  const valid = await formRef.value.validate()
  if (!valid) return

  // 提交请求
  try {
    const data = {
      ...form.value,
      memberId1: form.value.memberId,
      memberId2: form.value.relatedMemberId,
      createTime: new Date().toISOString()
    }
    if (data.id) {
      await RelationshipsApi.updateRelationships(data)
      message.success(t('common.updateSuccess'))
    } else {
      await RelationshipsApi.createRelationships(data)
      message.success(t('common.createSuccess'))
    }
    dialogVisible.value = false
    // 发送操作成功的事件
    emit('success')
  } catch {}
}

/** 取消按钮 */
const cancel = () => {
  dialogVisible.value = false
  reset()
}

/** 表单重置 */
const reset = () => {
  form.value = {
    id: undefined,
    memberId: undefined,
    relationType: undefined,
    relatedMemberId: undefined
  }
  formRef.value?.resetFields()
}

const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
</script> 